/*
 * @Author: Bing.Chan
 * @Date: 2024-04-21 00:40:59
 * @LastEditTime: 2024-05-30 10:05:21
 */
import MsgCmd from "./enums/MsgCommand"


const SERVER_HOST = "ws://localhost:8080/ws";
var loopTimer: any = null;

export default class MySender {
    /**
    * 单例对象
    */
    private static instance: MySender = new MySender();

    /**
     * WebSocket
     */
    private webSocket: WebSocket | null = null;

    /**
     * 私有化类默认构造器
     */
    private constructor() {
    }

    /**
     * 获取单例对象
     */
    static getInstance(): MySender {
        return MySender.instance;
    }

    /**
     * 连接服务器
     * 
     * @param funCallback 回调函数
     */
    connect(funCallback: () => void): void {
        let strURL = `${SERVER_HOST}`;
        console.log(`准备连接服务器, URL = ${strURL}`);
        let oWebSocket = new WebSocket(strURL);

        // 连接服务器
        oWebSocket.onopen = (): void => {
            console.log(`已连接服务器, URL = ${strURL}`);
            this.webSocket = oWebSocket;
            if (null != funCallback) {
                funCallback();
            }
        }

        // 异常
        oWebSocket.onerror = (): void => {
            console.error(`连接异常, URL = ${strURL}`);
            this.webSocket = null;
        }

        // 断开服务器
        oWebSocket.onclose = (): void => {
            console.warn("服务器连接已关闭");
            this.webSocket = null;
        }

        // 收到消息
        oWebSocket.onmessage = (event: any) => {
            if (null == event ||
                null == event.data) {
                return;
            }
            const data = JSON.parse(event.data)
            // // 处理消息
            this.onMsgReceived(data.type, event.data);
        }
    }
    /**
    * 发送消息
    * 
    * @param msgCommand 消息编号
    * @param msgBody 消息体
    */
    sendMsg(msgCommand: String, msg: any): void {
        if (msgCommand == "" ||
            null == msg) {
            return;
        }

        if (null == this.webSocket) {
            console.error("WebSocket 尚未初始化");
            this.closeService();
            return;
        }
        console.log(`发送消息, msgCommand = ${msgCommand}`);
        this.webSocket.send(JSON.stringify({
            ...{ type: msgCommand },
            ...msg
        }));
    }

    /**
     * 当收到消息
     * 
     * @param msgCommand 消息编号
     * @param msgBody 消息体
     */
    onMsgReceived(msgCommand: String, msg: String): void {
        if (msgCommand == "" ||
            null == msg) {
            return;
        }
    }
    /**
     * 心跳
     * @param userId
     */
    heartbeatLoop() {
        let loop = () => {
            if (this.webSocket == null) {
                console.error("[心跳失败]未连接")
                return;
            }
            console.log("send ping...")
            this.sendMsg(MsgCmd.HEAT_BEAT, { pong: "1" });
        }
        loopTimer = setInterval(loop, 3000);
    }

    /**
     * 心跳停止
     */
    heartbeatStop() {
        if (loopTimer) clearInterval(loopTimer);
    }

    closeService() { }

    close() {
        this.webSocket && this.webSocket.close();
    }
}